#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground

function preConfig()
{
echo "1" >/proc/sys/net/bridge/bridge-nf-call-iptables
echo "1" > /proc/sys/net/ipv4/ip_forward
# 关闭交换分区
swapoff -a
sed -i /swap/d /etc/fstab
}

function onlineInstall()
{
# 提前下载镜像
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-apiserver:v1.19.0
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-controller-manager:v1.19.0
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-scheduler:v1.19.0
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/kube-proxy:v1.19.0
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.2
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:3.4.9-1
docker pull registry.cn-hangzhou.aliyuncs.com/google_containers/coredns:1.7.0

docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-apiserver:v1.19.0 k8s.gcr.io/kube-apiserver:v1.19.0
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-controller-manager:v1.19.0 k8s.gcr.io/kube-controller-manager:v1.19.0
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-scheduler:v1.19.0 k8s.gcr.io/kube-scheduler:v1.19.0
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/kube-proxy:v1.19.0 k8s.gcr.io/kube-proxy:v1.19.0
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.2 k8s.gcr.io/pause:3.2
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/etcd:3.4.9-1 k8s.gcr.io/etcd:3.4.9-1
docker tag registry.cn-hangzhou.aliyuncs.com/google_containers/coredns:1.7.0 k8s.gcr.io/coredns:1.7.0

# 添加阿里云仓库
cat <<EOF | tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

# 安装kubeadm
yum install -y kubelet-1.19.0 kubeadm-1.19.0 kubectl-1.19.0 --disableexcludes=kubernetes
systemctl enable --now kubelet

kubeadm version
kubectl version
}

function installK8s()
{
 #1.在frames.txt中查看是否需要安装flink
 k8sInfo=`egrep "^k8s" $PLAY_HOME/frames.txt`

 k8s=`echo $k8sInfo | cut -d " " -f1`
 isInstall=`echo $k8sInfo | cut -d " " -f2`
 k8sNodes=`echo $k8sInfo | cut -d " " -f3` 
 masterNode=`echo $k8sInfo | cut -d " " -f4` 
 node=`hostname`

 masterInfo=`egrep "$masterNode" $PLAY_HOME/host_ip.txt`
 masterIP=`echo $masterInfo | cut -d " " -f1`

 #是否安装
 if [[ $isInstall = "true" && $k8sNodes =~ $node ]];then
    
     # 对节点进行配置 
     preConfig
     
     #2.查看/opt/frames目录下是否有k8s安装包
     k8sIsExists=`find /opt/frames -name $k8s`

     if [[ ${#k8sIsExists} -ne 0 ]];then
        # 离线方式安装
        echo "离线方式安装K8S"
     else
         echo "/opt/frames目录下没有k8s安装包，开始在线安装"
         onlineInstall         
     fi
 else
     echo "K8S不允许安装在当前节点，请检查配置文件！"
 fi

}

installK8s
